package com.twu.biblioteca.Domain;

import com.twu.biblioteca.Entity.Book;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hjli on 9/10/14.
 */
public class BookService {
    private List<Book> allBooks;
    private List<Book> booksOnShelf;

    public List<Book> getBooksOnShelf() {
        return booksOnShelf;
    }

    public BookService(){
        allBooks = new ArrayList<Book>();
        booksOnShelf = new ArrayList<Book>();
        Book book_one = new Book("1","Head First Java","Kathy Sierra and Bert Bates","Feb 9,2005");
        Book book_two = new Book("2","Effective Java","Joshua Bloch","May 28,2008");
        allBooks.add(book_one);
        allBooks.add(book_two);
        booksOnShelf.addAll(allBooks);
    }


    public String listBooks(){
        String result = "";
        for(Book book : this.booksOnShelf){
            result += "\n"+book.toString();
        }
        return result.replaceFirst("\\\\n","");
    }

    public String returnTo(String input) throws Exception {
        Book book = this.isReturnValid(input);
        String result;
        if( book != null){
            this.booksOnShelf.add(book);
            result = "Thank you for returning the movie.";
        }
        else{
            result = "That is not a valid movie to return.";
        }
        return result;
    }

    public Book isReturnValid(String input) {
        Book result = null;
        List<Book> allBooks = this.allBooks;
        if(input!=null && !input.isEmpty()){
            for(Book book : allBooks){
                if(input.equals(book.getId()))
                    result = book;
                break;
            }
        }
        return result;
    }

    public String checkout(String input) throws Exception{
        Book book = this.isBorrowValid(input);
        String result;
        if(book != null){
            booksOnShelf.remove(book);
            result = "Thank you! Enjoy the Book.";
        }
        else{
            result = "That book is not available.";
        }
        return result;
    }

    public Book isBorrowValid(String input) {
        Book result = null;
        List<Book> booksOnShelf = this.booksOnShelf;
        if(input!=null && !input.isEmpty()){
            for(Book book : booksOnShelf){
                if(input.equals(book.getId())){
                    result = book;
                    break;
                }
            }
        }
        return result;
    }
}
